/**
 * router.js路由模块
 * 职责：
 *      处理路由
 *      根据不同的请求方法+请求路径设置具体的请求函数
 * 模块职责要单一，我们划分模块的目的就是增强代码的可维护性，提升开发效率
 */

// Express专门提供了一种更好的方式
// 专门用来提供路由的
const express = require('express');
// 1 创建一个路由容器
const router = express.Router();
const pool = require('./controllers/ConnectMysql')

const jwt = require('jsonwebtoken');
let token;
// 2 把路由都挂载到路由容器中

router.get('/islogin', function (req, res) {

  // //解析token
  // let payload2 = jwt.verify(token, secret)

  //异步操作  我选择用promise来获取操作后的结果
  //首先判断用户名是否存在， 如果存在则进行判断账号密码是否正确
  new Promise((response, reject) => {
    const checkhassql = "select username from vess_user where username = '" + req.query.username + "'";
    pool.getConnection((err, conn) => {
      if (err) {
        console.log(err)
      } else {
        conn.query(checkhassql, (err, result) => {
          if (err) {
            reject(err)
          }
          response(result)  //不管是否查询到 都传递下去
        })
      }
      conn.release();
    })
  }).then(result => {
    if (result.length <= 0) {
      const noresult = { }
      noresult.ErrorCode = 404
      noresult.ErrorMessage = "该用户不存在，请进行注册"
      return res.send(noresult)
    } else {
      new Promise((response, reject) => {
        const isrightsql = "select * from vess_user where username='" + req.query.username + "' and password = '" + req.query.password + "' "
        pool.getConnection((err, conn) => {
          if (err) {
            console.log(err)
          } else {
            conn.query(isrightsql, (err, result) => {
              if (err) {
                reject(err)
              }
              response(result)  //不管是否查询到 都传递下去
            })
          }
          conn.release();
        })
      }).then(result => {
        if (result.length > 0) {   //如果大于0   则说名账号密码正确

          new Promise((response, reject) => {
            pool.getConnection((err, conn) => {
              if (err) {
                console.log(err)
              } else {
                const isrightsql = "select isAdmin from vess_user where username='" + req.query.username + "' and password = '" + req.query.password + "' "
                conn.query(isrightsql, (err, result) => {
                  if (err) {
                    reject(err)
                  }
                  response(result)  //不管是否查询到 都传递下去
                })
              }
              conn.release();
            })
          }).then(result => {
            if (result[0].isAdmin != 1) {
              result[0].ErrorCode = 401
              result[0].ErrorMessage = "对不起,您不是管理员,暂时无法登录"
              return res.send(result[0])
            } else {
              let payload = req.query;
              let secret = 'vess_xfy';
              token = jwt.sign(payload, secret);
              result[0].ErrorCode = 200
              result[0].token = token
              result[0].ErrorMessage = "登录成功"
              return res.send(result[0])
            }
          })
        } else {
          const iserrresult = { }
          iserrresult.ErrorCode = 404
          iserrresult.ErrorMessage = "账号或密码错误"
          return res.send(iserrresult)
        }
      })
    }
  }).catch(err => {
    const serviceerr = { }
    serviceerr.ErrorCode = 501
    serviceerr.ErrorMessage = "服务器繁忙,请稍后重试"
    return res.send(serviceerr)

  })
});

router.get('/productInfo', (req, res) => {
  // console.log(req.headers.authorization)
  // console.log(token)
  if (token == undefined || req.headers.authorization !== token) {
    return res.status(401).json({
      code: 401, message: "请先登录"
    })
  }
  console.log(req.query)
  let ProductList;
  let showpage = (req.query.page - 1) * req.query.limit
  let showlimit = parseInt(req.query.limit)

  if (req.query.condition !== "") {
    ProductList = `select *, (select count(*)  from vess_goods
     where concat(id,goodsname,goodsprice,desction,store,kind) like '%${req.query.condition}%' and isDelete=0) counts
     from vess_goods where concat(id,goodsname,goodsprice,desction,store,kind) like '%${req.query.condition}%' and isDelete=0 limit ${showpage},${showlimit} `;
  } else {
    ProductList = `select *,(select count(*) from vess_goods) counts from vess_goods where isDelete = 0 limit ${showpage},${showlimit}`;
  }
  new Promise((response, reject) => {
    pool.getConnection((err, conn) => {
      if (err) {
        console.log(err)
      } else {
        conn.query(ProductList, (err, result) => {
          if (err) {
            reject(err)
            console.log(err)
          }
          response(result)  //不管是否查询到 都传递下去
        })
      }
      conn.release();
    })
  }).then(result => {
    console.log("请求了一次列表")
    res.send(result)
  })
})

router.post('/edit', (req, res) => {
  let updatesql = `update vess_goods
   set goodsname ="${req.body.goodsname}",goodsprice ="${req.body.goodsprice}" ,kind="${req.body.kind}",desction="${req.body.desction}", store="${req.body.store}"
   where id = ${req.body.id}`;
  new Promise((resovle, reject) => {
    pool.getConnection((err, conn) => {
      if (err) {
        console.log(err)
      } else {
        conn.query(updatesql, (err, result) => {
          if (err) {
            return reject(err)
          }
          resovle(result)
          console.log("更新成功")
        })
      }
      conn.release();
    })
  }).then(result => {
    const edit = { }
    edit.ErrorCode = 200
    edit.ErrorMessage = "操作成功"
    res.send(edit);
  })
})

router.delete('/deleteOne', (req, res) => {
  console.log("收到请求了")
  console.log(req.body)
  let updatesql = "update vess_goods set isDelete=1 where id= '" + req.body.id + "'";
  new Promise((resovle, reject) => {
    pool.getConnection((err, conn) => {
      if (err) {
        console.log(err)
      } else {
        conn.query(updatesql, (err, result) => {
          if (err) {
            return reject(err)
          }
          resovle(result)
          console.log("删除成功")
        })
      }
      conn.release();
    })
  }).then(result => {
    const deleteres = { }
    deleteres.ErrorCode = 200
    deleteres.ErrorMessage = "操作成功"
    res.send(deleteres);
  })
})

router.delete('/deleteSome', (req, res) => {
  let sql = `update vess_goods set isDelete =1 where id in (${req.body.deletelist})`
  console.log(sql)
  new Promise((resovle, reject) => {
    pool.getConnection((err, conn) => {
      if (err) {
        console.log(err)
      } else {
        conn.query(sql, (err, result) => {
          if (err) {
            return reject(err)
          }
          resovle(result)
          console.log("删除成功")
        })
      }
      conn.release();
    })
  }).then(res => {
    const deleteres = { }
    deleteres.ErrorCode = 200
    deleteres.ErrorMessage = "操作成功"
    res.send(deleteres);
  })
  res.send()
})

// 3 把router导出
module.exports = router;